package com.beiding.jsonanalyzer.analyze.func.openfunc;

import com.beiding.jsonanalyzer.analyze.func.*;
import com.beiding.jsonanalyzer.analyze.func.base.CollectionFuncAdaptor;
import com.beiding.jsonanalyzer.analyze.func.base.EasyFunc;
import com.beiding.jsonanalyzer.flow.ValueNode;
import com.beiding.jsonanalyzer.utils.TextUtils;

import java.util.*;

/**
 * 日期格式化
 *
 * @author 丁常磊
 * @date 2022/5/19 11:23
 */

public class ForEach {

    public static CollectionFunc of(Object key, Object by) {
        FuncFactory funcFactory = FuncUtils.ensureFuncFactory(by);
        return FuncUtils.buildForEasyFunc(new CollectionFuncAdaptor<EasyFunc>() {
            @Override
            protected EasyFunc newInstance() {
                FuncBase instance = funcFactory.createInstance();
                return new EasyFunc() {
                    @Override
                    protected Object execute(Object o) {
                        Collection collection = null;
                        if (o instanceof Collection) {
                            collection = (Collection) o;
                        } else if (o instanceof Object[]) {
                            collection = Arrays.asList((Object[]) o);
                        }
                        if (collection != null) {
                            List r = new ArrayList();
                            for (Object o1 : collection) {
                                ValueNode valueNode = new ValueNode();
                                valueNode.set(o1);
                                Object o2 = instance.executeOne(valueNode);
                                r.add(o2);
                            }

                            return r;
                        }
                        return null;
                    }
                    @Override
                    public String toString() {
                        return "foreach(\n" + TextUtils.addFormat(core,"\t") + ",\n" + TextUtils.addFormat(instance,"\t") + ")";
                    }
                };
            }
        }, key);

    }

}
